package com.pushtime.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pushtime.config.Constants;
import com.pushtime.service.GeneratorService;
import com.pushtime.service.dto.JhipsterDTO;
import com.pushtime.service.lib.PtEngine;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;

@Service
public class GeneratorServiceImpl implements GeneratorService {

    @Value("${application.generator.project}")
    private String projectPath;
    private final ObjectMapper objectMapper;
    private final PtEngine ptEngine;

    public GeneratorServiceImpl(ObjectMapper objectMapper, PtEngine ptEngine) {
        this.objectMapper = objectMapper;
        this.ptEngine = ptEngine;
    }

    /**
     * 生成 jhipster 查询代码
     */
    @Override
    public void generate() {
        // 读取 jhipster 生成的 JSON 目录结构
        String jhipsterPath =  projectPath + Constants.SPLIT + Constants.JHIPSTER_DIR;
        File fileDir = new File(jhipsterPath);
        try {
            if (fileDir.isDirectory()) {
                File[] files = fileDir.listFiles(file -> file.getName().endsWith(Constants.JSON_FILE));
                if (files != null) {
                    for (File file : files) {
                        JhipsterDTO jhipsterDTO = objectMapper.readValue(file, JhipsterDTO.class);
                        generate(jhipsterDTO);
                    }
                }
            }
        } catch (SecurityException|IOException e){
            e.printStackTrace();
        }

    }

    /**
     * 生成 jhipster 对象
     *
     * @param jhipsterDTO jhipster 提供的生成信息
     */
    private void generate(JhipsterDTO jhipsterDTO) {
        Constants.paths.forEach((key, value) -> {
            try {
                ptEngine.generate(jhipsterDTO, key, value);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }


}

